package com.box.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.box.annotation.SysLog;
import com.box.entity.DbAdmin;
import com.box.entity.DbArticletype;
import com.box.entity.DbRoles;
import com.box.entity.DbUsers;
import com.box.entity.DbWeb;
import com.box.entity.ResultAdminLog;
import com.box.entity.UserSearch;
import com.box.service.AdminService;
import com.box.service.ArticleTypeService;
import com.box.service.RolesService;
import com.box.service.UserService;
import com.box.service.WebService;
import com.box.utils.GlobalError;
import com.box.utils.JsonUtils;
import com.box.utils.LayuiResult;
import com.box.utils.RRException;
import com.box.utils.RandomValidateCode;
import com.box.utils.ResponseResult;
import com.box.utils.SessionUtils;
import com.box.utils.ShiroUtils;


/**
*<p>Title:AdminController.java</p>
*<p>Description:管理员控制器</p>
*<p>Company:www.99weixinxcx.cn</p>
*@author 陕西电子科技学院:滕一帆
*@date	2019年4月6日下午10:24:46
*@version 1.0
*
*
*
 */
@Controller
@RequestMapping("/admin")
public class AdminController {
	
	@Autowired
private	AdminService adminService;
	
	@Autowired
	private ArticleTypeService typService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private RolesService roleService;
	
	@Autowired
	private WebService webService;

	//全局错误信息
	private String error=GlobalError.ERROR;
	
	//错误页面提示运行时间
	private long runtime=GlobalError.currentTime;
	
	//提示个人信息
	private String info=GlobalError.INFO;


	@SysLog("后台登录")
	@RequestMapping("/shiro/login")
	@ResponseBody
	public LayuiResult login(String userName, String passWord,String vcode) {
		if(StringUtils.isEmpty(userName)||StringUtils.isEmpty(passWord)||StringUtils.isEmpty(vcode)){
	
			return LayuiResult.error("参数不能为空");
		}
		
					System.out.println(userName+passWord+ vcode+".............................用户名和密码还有验证码");
		
			String sessionValues = SessionUtils.getSessionAttribute(RandomValidateCode.RANDOMCODEKEY).toString();
			System.out.println(sessionValues+"...........session中的验证码");
		
				try{

					//md5加密
					passWord=DigestUtils.md5DigestAsHex(passWord.getBytes());
					UsernamePasswordToken token = new UsernamePasswordToken(userName, passWord);
					Subject subject = SecurityUtils.getSubject();
					if(vcode.equals(sessionValues)){
						if(!subject.isAuthenticated()){
							token.setRememberMe(true);  //记住密码
							subject.login(token);//验证角色和权限
							System.out.println("第二次走的判断");
							return LayuiResult.ok();
						}else{
							subject.login(token);//验证角色和权限
							System.out.println("第一次登录走的判断");
							return LayuiResult.ok();
						}
					}

					return LayuiResult.error("验证码不正确");
				}catch (UnknownAccountException e) {
					return LayuiResult.error(e.getMessage());
				}catch (IncorrectCredentialsException e) {
					return LayuiResult.error(e.getMessage());
				}catch (LockedAccountException e) {
					return LayuiResult.error(e.getMessage());
				}catch (AuthenticationException e) {
					return LayuiResult.error("账户验证失败");
				}
			

			


	

		
	}


	
	
	//管理员注册
	
	@SysLog("管理员注册")
	@RequestMapping(value="/register",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public String register(String userName,String  passWord){
		DbAdmin admin=new DbAdmin();
		admin.setUsername(userName);
	
		String md5 = DigestUtils.md5DigestAsHex(passWord.getBytes());
		admin.setPassword( md5);
		
		try {
			  ResponseResult register = adminService.register(admin);
String json = JsonUtils.objectToJson(register);
			return  json;
		} catch (Exception e) {
			// TODO: handle exception
			ResponseResult build = ResponseResult.build(500, "注册失败");
	String error=		 JsonUtils.objectToJson(build);
			return error ;
		}
	
	}
	
	@SysLog("管理员信息界面")
	//返回队形
	@RequestMapping(value="/adminMsg",method={RequestMethod.GET,RequestMethod.POST})
	public String getadminsmsg(Model model){
			
		
		try {
			DbAdmin admin= adminService.getDbAdminItems();
			model.addAttribute("admin", admin);
			return "adminMsg";
		} catch (Exception e) {
			// TODO: handle exception
	model.addAttribute("error", error);
	model.addAttribute("runtime", runtime);
	model.addAttribute("info", info);
			return "error/404";
		}
		
		
		
	}
	
	//返回队形
		@RequestMapping(value="/adminUser",method={RequestMethod.GET,RequestMethod.POST})
		public String getAdminUser(Model model){
			
					
			try {
				DbAdmin admin= adminService.getDbAdminItems();
				model.addAttribute("admin", admin);
				return "adminUser";
			} catch (Exception e) {
				// TODO: handle exception
				model.addAttribute("error", error);
				model.addAttribute("runtime", runtime);
				model.addAttribute("info", info);
				return "error/404";
			}
		}
		
		@RequestMapping(value="/addUser",method={RequestMethod.GET,RequestMethod.POST})
		@ResponseBody
		public String getAdminUser(DbAdmin admin){
			
			 ResponseResult addUser = adminService.addUser(admin);
			 String objectToJson = JsonUtils.objectToJson(addUser);
			System.out.println(addUser+"..................成功记录");
			return objectToJson;
			
		}
		
		//退出界面
		@SysLog("退出后台管理界面")
		@RequestMapping(value="/logout",method={RequestMethod.GET,RequestMethod.POST})
		public String LogOut(Model model) {
			
			 adminService.LogOut();
			 DbWeb back = webService.selWebByOne(3);
				model.addAttribute("web", back);
				
			return "login";
			
		}
		
		@RequestMapping(value="/welcome",method={RequestMethod.GET,RequestMethod.POST})
		public String showlog(Model model){
		
			
			
			try {
				DbAdmin dbAdminItems = adminService.getDbAdminItems();
				model.addAttribute("admin", dbAdminItems );
				
				 List<ResultAdminLog> list = adminService.selectByAdminlog();
				 
				 model.addAttribute("adminlog", list);
				 return "welcome";
			} catch (Exception e) {
				// TODO: handle exception
				
				model.addAttribute("error", error);
				model.addAttribute("runtime", runtime);
				model.addAttribute("info", info);
				return "error/404";
			}
			
			
		}
		
		
		@RequestMapping(value="/articleList",method={RequestMethod.GET,RequestMethod.POST})
		public String showList(Model model){
	
	
			
			
			try {
				DbAdmin dbAdminItems = adminService.getDbAdminItems();
				model.addAttribute("admin", dbAdminItems );
				
				 List<ResultAdminLog> list = adminService.selectByAdminlog();
				 
				 model.addAttribute("adminlog", list);
				 
				 List<DbArticletype> typelist = typService.getArticleTypeList();
				 
				 model.addAttribute("articletype", typelist );
				 
				 List<DbUsers> userList = userService.getUserList();
				 
				 model.addAttribute("user", userList);
					return "article/articleList";
				
			} catch (Exception e) {
				// TODO: handle exception
				model.addAttribute("error", error);
				model.addAttribute("runtime", runtime);
				model.addAttribute("info", info);
				return "error/404";
			}
			
	
			
		}
		
		
		
		
		
		
	
		@RequestMapping("/userList")
		public String showUsersListPage(Model model){
		
			
			try {
				DbAdmin dbAdminItems = adminService.getDbAdminItems();
				model.addAttribute("admin", dbAdminItems);
				return "userList";
			} catch (Exception e) {
				// TODO: handle exception
				model.addAttribute("error", error);
				model.addAttribute("runtime", runtime);
				model.addAttribute("info", info);
				return "error/404";
			}
			
		}
		
		@RequestMapping(value="/user/getUserList",method={RequestMethod.GET,RequestMethod.POST},produces="application/json;charset=UTF-8")
		@ResponseBody
		public LayuiResult getUserList(Integer page,Integer limit,UserSearch search){
			System.out.println(search.getNickname()+"..............昵称");
			System.out.println(search.getUsername()+"..............用户名");
			System.out.println(search.getEmail()+"..............邮箱");
			System.out.println(search.getSex()+"..............性别");
			LayuiResult selUsers = userService.selUsers(page, limit, search);
			return selUsers;
		}
		
		@RequestMapping("/goPage")
		public String showAddUserPage(Model model){
			
			
			try {
				DbAdmin dbAdminItems = adminService.getDbAdminItems();
				model.addAttribute("admin", dbAdminItems);
				return "user/addUser";
			} catch (Exception e) {
				// TODO: handle exception
				model.addAttribute("error", error);
				model.addAttribute("runtime", runtime);
				model.addAttribute("info", info);
				return "error/404";
			}
	
		}
		

		
		/**
		 * 批量删除指定管理员
		 * @return
		 */
		@RequestMapping("/delAdmins/{adminStr}")
		@RequiresPermissions("sys:admin:delete")
		@ResponseBody
		public LayuiResult delAdmins(@PathVariable("adminStr") String adminStr) {
			String[] strs = adminStr.split(",");
			for (String str : strs) {
				DbAdmin admin = (DbAdmin)SecurityUtils.getSubject().getPrincipal();
				if((admin.getAid()==Long.parseLong(str))){
					return LayuiResult.error();
				}
				if("1".equals(str)){
					return LayuiResult.error();
				}
			}
			try {
				adminService.delAdmins(adminStr);
				return LayuiResult.ok();
			} catch (Exception e) {
				e.printStackTrace();
				return LayuiResult.error();
			}
		}
		
		
		/**
		 * 管理员用户名唯一性检查
		 * @return
		 */
		@RequestMapping(value="/checkAdminName/{username}",method={RequestMethod.GET,RequestMethod.POST})
		@ResponseBody
		public LayuiResult checkAdminName(@PathVariable("username") String username) {
			System.out.println(username+"...............我进来了查询用户管理员用户名唯一性");
			DbAdmin admin = adminService.selAdminByUserName(username);
			if(admin!=null){
				return new LayuiResult(500,"管理员已存在！");
			}
			return new LayuiResult(0,"管理员用户名可以使用");
		}
		/**
		 * 管理员列表
		 * @param page
		 * @param limit
		 * @return
		 */
		@RequestMapping("/getAdminList")
		@RequiresPermissions("sys:admin:list")
		@ResponseBody
		public LayuiResult getAdminList(Integer page,Integer limit) {
			LayuiResult admins = adminService.selAdmins(page, limit);
			return admins;
		}
		
		@RequestMapping("/delAdminById/{aid}")
		@RequiresPermissions("sys:admin:delete")
		@ResponseBody
		public LayuiResult delAdminById(@PathVariable("aid") String aid) {
			
			if(aid.equals("1")){
				return LayuiResult.error();
			}
			try {
				adminService.delAdminById(Long.parseLong(aid));
				return LayuiResult.ok();
			} catch (Exception e) {
				e.printStackTrace();
				return LayuiResult.error();
			}
		}
		
		
		@RequestMapping("/insAdmin")
		@RequiresPermissions("sys:admin:save")
		@ResponseBody
		public LayuiResult insAdmin(DbAdmin admin) {
			//防止浏览器提交
			DbAdmin a = adminService.selAdminByUserName(admin.getUsername());
			if(a!=null){
				return new LayuiResult(500, "用户名已存在,请重试！");
			}
			adminService.insAdmin(admin);
			return LayuiResult.ok();
		}
		/**
		 * 更新管理员信息
		 * @param admin
		 */

		@RequestMapping("/updAdmin")
		@RequiresPermissions("sys:admin:update")
		@ResponseBody
		public LayuiResult updAdmin(DbAdmin admin) {
			if(admin!=null&&admin.getAid()==1){
				return LayuiResult.error("不允许修改!");
			}
			try {
				adminService.updAdmin(admin);
				return LayuiResult.ok();
			} catch (Exception e) {
				e.printStackTrace();
				return LayuiResult.error();
			}
		}

		/**
		 * 
		 * 页面跳转
		 * 
		 * 
		 * 
		 */
		@RequestMapping("/page/adminList")		
		public String showAdminListPage() {
		
			return "admin/adminList";
		}
		
	
		

		
		
		@RequestMapping("/page/addAdmin")
		@RequiresPermissions("sys:admin:save")
		public String addAdmin(Model model){
			
		
			try {
				List<DbRoles> roles = roleService.selRoles();
				model.addAttribute("roles", roles);
				return "admin/addAdmin";
			} catch (Exception e) {
				// TODO: handle exception
				model.addAttribute("error", error);
				model.addAttribute("runtime", runtime);
				model.addAttribute("info", info);
				return "error/404";
			}
	
		}
		
		@RequestMapping("/page/editAdmin/{aid}")
		@RequiresPermissions("sys:admin:update")
		public String editAdmin(Model model,@PathVariable("aid") String aid) {
			DbAdmin ad = adminService.selAdminById(Integer.parseInt(aid));
			List<DbRoles> roles = roleService.selRoles();		
			model.addAttribute("ad",ad);
			model.addAttribute("roles", roles);
			return "admin/editAdmin";
		}
		
		/**
		 * 验证码controller
		 * 
		 */
		/**
		 * 获取生成验证码显示到 UI 界面
		 * @param request
		 * @param response
		 * @throws ServletException
		 * @throws IOException
		 */
		@RequestMapping(value="/checkCode")
		public void checkCode(HttpServletRequest request, HttpServletResponse response)
	            throws ServletException, IOException {
			//设置相应类型,告诉浏览器输出的内容为图片
	        response.setContentType("image/jpeg");
	        
	        //设置响应头信息，告诉浏览器不要缓存此内容
	        response.setHeader("pragma", "no-cache");
	        response.setHeader("Cache-Control", "no-cache");
	        response.setDateHeader("Expire", 0);
	        
	        RandomValidateCode randomValidateCode = new RandomValidateCode();
	        try {
	            randomValidateCode.getRandcode(request, response);//输出图片方法
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
		}
		
}
